'use strict';

class StringUtil {
  /**
   * 解析多个栏目字符串
   * @param {String} oldColumn 老栏目
   * @param {Object[]} realMapping 老栏目名称与excel中名称的mapping
   * @param {String} realMapping[].value excel中老栏目名
   * @param {String} realMapping[].realValue 数据库中老栏目名
   * @return {Array} [{"name":"住房改革与发展","parent":{"name":"首页"}},{"name":"工作动态","parent":{"name":"党建工作","parent":{"name":"首页"}}},{"name":"工作动态","parent":{"name":"离退休干部工作","parent":{"name":"首页"}}},{"name":"对外合作","parent":{"name":"对外交流与合作","parent":{"name":"首页"}}}]
   */
  static splitOldColumn(oldColumn, realMapping) {
    if (!oldColumn) {
      return oldColumn;
    }
    const trimOldColumn = oldColumn.trim();
    if (trimOldColumn.length === 0) {
      return oldColumn;
    }

    // const columns = trimOldColumn.indexOf('；') >= 0 ? trimOldColumn.split('；') : trimOldColumn.split(';');
    const columns = trimOldColumn.split(/[;；]/g);
    const result = [];
    // 提取每个栏目的父栏目
    columns.forEach(column => {
      let splitor = '>';
      if (column.indexOf('>>') >= 0) {
        splitor = '>>';
      }
      const columnLevels = column.split(splitor).filter(m => m.trim().length > 0).reverse();
      if (columnLevels && columnLevels.length > 0) {
        const current = {};
        let lastCurrent = null;
        columnLevels.forEach((cl, index) => {
          cl = StringUtil.getRealParentName(cl.trim(), realMapping);
          if (index === 0) {
            current.name = cl;
            current.fullname = column;
            lastCurrent = current;
          } else {
            while (index-- >= 0 && lastCurrent.parent) {
              lastCurrent = lastCurrent.parent;
            }
            lastCurrent.parent = { name: cl };
          }
        });
        result.push(current);
      }
    });
    return result;
  }

  static getRealParentName(name, realMapping) {
    if (!realMapping) {
      return name;
    }
    const findOne = realMapping.find(m => m.value === name);
    return findOne ? findOne.realValue : name;
  }
  static splitTypeColumn(typeColumn) {
    if (!typeColumn) {
      return typeColumn;
    }
    const trimTypeColumn = typeColumn.trim();
    if (trimTypeColumn.length === 0) {
      return typeColumn;
    }

    const columns = trimTypeColumn.split('，');
    return columns;
  }
}

module.exports = StringUtil;
